<template>
  <div class="page-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="16">
          <el-row>
            <el-date-picker
                v-model="dateList"
                type="daterange"
                unlink-panels
                range-separator=" - "
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                :shortcuts="shortcuts"
                size="small"
                @change="selectTimes"
                style="flex-grow: 0;width: 240px"
            />
            <el-select v-model="params.code" size="small" placeholder="选择单据类型" clearable filterable style="margin: 0 15px;width: 150px">
              <el-option v-for="item in matterList" :key="item.id" :label="item.name" :value="item.code"/>
            </el-select>
<!--            <el-input v-model="params.streamNo" size="small" clearable placeholder="单据号" style="width: 170px"/>-->
            <el-input v-model="params.invoiceNo" size="small" clearable placeholder="发票号" style="width: 170px"/>
            <el-button size="small" type="primary" @click="getTableList" icon="ele-Search" style="margin-left: 15px">查询</el-button>
            <el-button size="small" @click="onReset" icon="ele-Refresh">重置</el-button>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row justify="end">
            <el-button type="primary" size="small">新增已开发票</el-button>
          </el-row>
        </el-col>
      </el-row>

      <div class="table-box">
        <el-table :data="tableList" border size="small" class="tableList" :span-method="tableSpan" :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
          <el-table-column prop="targetName" label="公司/个人"/>
          <el-table-column label="所有订单总额">
            <template v-slot="{row}">
              <p>{{ row.totalAmount }}</p>
              <el-button type="primary" link size="small" @click="">【查看所有订单】</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="invoiceTotal" label="已开发票总额"/>
          <el-table-column label="单据">
            <template v-slot="{row}">
              <el-button size="small" v-if="row['agendaMatter']" type="primary" text link @click="skip">
                {{ row['agendaMatter']['codeName'] + ' - ' + (row.streamNo || row['agendaMatter']['info']['capitalStreamNo']) }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="开票类型">
            <template v-slot="{row}">{{ row.type == 1 ? '普通发票' : '专用发票' }}</template>
          </el-table-column>
          <el-table-column prop="amount" label="金额"/>
          <el-table-column label="关联">
            <template v-slot="{row}">
              <template v-if="row['agendaMatter'] && row['agendaMatter']['relateItems']">
                <div v-for="item in row['agendaMatter']['relateItems']" v-show="item.label.indexOf('员工') < 0 && item.label.indexOf('客') < 0" :key="item.id">{{ item.label.replace('/', '：') }}</div>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="invoiceNum" label="发票号码"/>
          <el-table-column prop="confirmDate" label="日期"/>
          <el-table-column label="创建人/部门">
            <template v-slot="{row}">
              <span v-if="row['agendaMatter']">{{ row['agendaMatter']['sponsor'].userName + '/' + row['agendaMatter']['sponsor']['oaDeptName'] }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column align="center" label="操作" >-->
          <!--            <template v-slot="scope">-->
          <!--              <el-button size="small" type="primary" link @click="viewDetail(scope.row)">查看发票详情</el-button>-->
          <!--              <el-button size="small" type="primary" link @click="viewOrder(scope.row)">查看订单</el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
        <div class="page-block">
          <el-pagination
              v-model:currentPage="params.current"
              v-model:page-size="params.size"
              :page-sizes="[10, 20, 30, 40]"
              :small="true"
              :disabled="false"
              :background="false"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :hide-on-single-page="true"
              @size-change="sizeChange"
              @current-change="getTableList"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增已开发票 -->
<!--    <el-dialog v-model="invoicingVisible" title="新增已开发票" destroy-on-close width="560px">-->
<!--      <div class="mb-2 flex items-center text-sm">-->
<!--        <el-form :model="invoicingForm" :rules="invoicingRules" size="small" ref="invoicingFormRef" label-width="110px" class="drawer-form">-->
<!--          <el-form-item prop="customId" label="客户：">-->
<!--            <el-input v-model="invoicingForm.customId" placeholder="客户" style="width: 250px;"/>-->
<!--          </el-form-item>-->
<!--          <el-form-item prop="receivableAccount" label="应收总额：">-->
<!--            <el-input v-model="invoicingForm.receivableAccount" placeholder="应收总额" style="width: 250px;"/>-->
<!--          </el-form-item>-->
<!--          <el-form-item prop="notReceived" label="应收未收：">-->
<!--            <el-input v-model="invoicingForm.notReceived" type="number" placeholder="应收未收" style="width: 250px;"/>-->
<!--          </el-form-item>-->
<!--          <el-form-item prop="invoiceAmount" label="已开发票总额：">-->
<!--            <el-input v-model="invoicingForm.invoiceAmount" type="number" placeholder="已开发票总额" style="width: 250px;"/>-->
<!--          </el-form-item>-->
<!--          <el-form-item prop="null" label="无原型图">-->

<!--          </el-form-item>-->
<!--        </el-form>-->
<!--      </div>-->
<!--      <template #footer>-->
<!--          <span class="dialog-footer">-->
<!--            <el-button size="small" @click="invoicingVisible = false">关闭</el-button>-->
<!--            <el-button size="small" type="primary" icon="ele-Check" @click="invoicingSubmit(invoicingFormRef)">提交</el-button>-->
<!--          </span>-->
<!--      </template>-->
<!--    </el-dialog>-->

    <create-invoice v-model:dialogDrawer="createInvoiceVisible" :type="matterType" @onSubmit="getTableList"/>

  </div>
</template>

<script>
import {reactive, toRefs, ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import CreateInvoice from '/@/views/matter/money/invoicing/CreateInvoice.vue'
import invoiceDispatchApi from '/@/api/money/invoiceDispatch'
import {getModuleMatters} from '/@/api/matter'

export default {
  name: 'Invoicing',
   components: {
    CreateInvoice
  },
  setup() {
    const invoicingFormRef = ref()
    const router = useRouter()
    const state = reactive({
      matterType:'0',
      invoicingVisible:false,
      createInvoiceVisible:false,
      invoicingForm:{
        customId:'',
        receivableAccount:'',
        notReceived:'',
        invoiceAmount:''
      },
      invoicingRules: {},
      params: {
        current: 1,
        size: 10,
        code: null,   // 事项编码（单据类型）
        invoiceNo: null,    // 发票号
        st: null,   // 开始时间
        et: null   // 结束时间
      },
      dateList: [],
      matterList: [],
      shortcuts: [
        {
          text: '最近半年',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 183)
            return [start, end]
          }
        },
        {
          text: '最近一年',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            return [start, end]
          }
        }
      ],
      total: 0,
      tableList: []

    })
    //获取数据
    const getTableList = () => {
      invoiceDispatchApi.getPage(state.params).then(res => {
        state.tableList = res.data.records
        state.total = res.data.total
      }).catch(e => console.log(e))
    }
    //打开新增已开发票
    const openCreate = () =>{
      state.createInvoiceVisible = true
    }
    //查看详情
    const viewDetail = () => {

    }
    //查看订单
    const viewOrder = () => {

    }
    //重置
    const onReset = () => {
      state.params = {
        current: state.params.current,
        size: state.params.size,
        code: null,
        invoiceNo: null,
        st: null,
        et: null
      }
      state.dateList = []
      getTableList()
    }
    //提交
    const invoicingSubmit = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (!valid) return // 必填没有填就直接结束
      })
    }
    //跳转
    const skip = (name, row) => {
      if (name) {
        router.push({name: name})
      }
    }
    //修改类型选择
    const selectType = (val) => {
      if (val) {
        getTableList()
      }
    }
    // 筛选时间
    const selectTimes = (val) => {
      if (val && val.length > 0) {
        state.params.st = val[0]
        state.params.et = val[1]
      } else {
        state.params.st = state.params.et = null
      }
      getTableList()
    }
    //table列合并
    const tableSpan = (item) => {
      let spanNum = 1
      if (item.columnIndex < 3) {
        spanNum = item.row.spanNum
      }
      return {
        rowspan: spanNum, // 合并的行数
        colspan: 1 // 合并的列数，为0表示不显示
      }
    }
    const sizeChange = (size) => {
      state.params.size = size
      state.params.current = 1
      getTableList()
    }

    onMounted(() => {
      getTableList()
      // 获取钱相关的事项列表
      getModuleMatters('Money').then(res => state.matterList = res.data).catch(e => console.log(e))
    })

    return {
      ...toRefs(state),
      invoicingFormRef,
      CreateInvoice,
      getTableList,
      openCreate,
      viewDetail,
      viewOrder,
      sizeChange,
      onReset,
      invoicingSubmit,
      skip,
      tableSpan,
      selectTimes,
      selectType
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .table-box {
    background: #fff;
    margin-top: 10px;

    :deep(.el-table__header-wrapper .el-table__cell) {
      background: var(--el-color-primary-light-9);
      color: var(--next-bg-menuBar-light-1);
    }

    :deep(thead .cell) {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :deep(thead .el-icon) {
      margin-top: -2px;
      cursor: pointer;
    }

    .primary {
      cursor: pointer;
      color: var(--el-color-primary);
    }

  }
}
</style>
